package com.cincc.general;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.cincc.general.common.AttrsConstant;
import com.cincc.general.common.SharePreferenceUtil;
import com.cincc.siphone.core.SipCoreCall;
import com.cincc.siphone.core.SipCoreEvent.CallState;
import com.cincc.siphone.core.SipCoreEvent;
import com.cincc.siphone.core.SipPhoneCtrl;
import com.cincc.siphone.websocket.WebSocketCtrl;


/**
 * 通话页面
 *
 * @author fengwawa
 */
public class CallActivity extends AppCompatActivity implements View.OnClickListener {

    TextView textCallNo;
    TextView textStatus;
    LinearLayout layoutInfo;

    RelativeLayout remoteContainer;

    LinearLayout layoutTool;

    Button btMute;
    Button btAnswer;
    Button btHandOff;
    Button btSpeaker;

    /**
     * 是否启用人脸检测功能
     */
    private boolean openFaceDetect = true;
    /**
     * 拨叫号码
     */
    private String callNumber;

    private SipPhoneCtrl mSipPhoneCtrl = SipPhoneCtrl.Instance();
    private Handler _mHandler = new Handler();

    private boolean mMuted = false;
    private boolean mSpeaker = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_call_landscape);
        initView();
        initData();

        initSipParam();
        makeCall();
    }

    /**
     * 拨打号码
     */
    private void makeCall() {
        String extraHeader = "Token:" + SDK_TOKEN +
                "|||X-CN-TOKEN:" + X_TOKEN +
                "|||X-CN-REMARK:" + remark; // 一些自定义数据  纯英文  不能中文
        // 注意：initial给回调则要检查与平台的连接。这是个耗时1~5秒的异步操作。与呼叫并不属于同个流程。
        // disconnect不能打断这个检查流程
        // 检查连接可以单独使用。检查完毕后可以呼出也可以不呼出，由开发者决定
        // 也可以不检查，传null表示不检查连接
        mSipPhoneCtrl.Initial(this, new SipPhoneCtrl.OneInitParamCallBack() {
            @Override
            public void onInitResult(int i) {
                Log.e("CallActivity", "onInitResult===>" + i);
                if (i == 200) {
                    runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            if (mSipPhoneCtrl.DoCall(String.format("%s@%s", callNumber, mSipPhoneCtrl.GetServer()), extraHeader)) {
                                //呼叫成功
                            } else {
                                textStatus.setText("呼叫状态错误，不允许外呼");
                            }
                        }
                    });
                } else {
                    Log.e("CallActivity", "Sip初始化失败");
                }
            }
        });
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        _mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                mSipPhoneCtrl.UnInitial();
            }
        }, 300);
    }

    //        final String serverUrl = "119.23.174.138"; // 服务地址  119.23.174.138 test env
    String serverUrl = "";
//    String serverUrl = "ipp.caih.com"; // 服务地址  119.23.174.138 pro env
//    final String serverUrl = "ipptest.caih.com"; // 服务地址  119.23.174.138 pro env

    String SDK_TOKEN = ""; // 后台分配 这里是正式环境用的
//    String SDK_TOKEN = "92f5d2dd285e47dcf4bbb1b40c0ae858"; // 后台分配 这里是正式环境用的
//    String SDK_TOKEN = "44a2254ddd70c236aac4cb21ec7df8b2"; // 后台分配 这里是测试环境用的

    String sdkId = "";
    //        String sdkId = "2df57125383ec6fb6ae307d6f58c2961";//测试环境
//    String sdkId = "b2d3443a8e3a24646a016f410764c51d";//正式环境
    String X_TOKEN = "eyJjcFVzZXJJZCI6InN0b19hcHBfcHJvZHVjdGlvbiIsImN1cnJlbnRUaW1lc3RhbXAiOjE3MTYyNjA1NDY4MDQsInJ0Y0lkIjoiMTAwNjAxMzM2NzYwMTY2NjI2NjMxODAifQ==.kJyAmNU85SPv34NrRhQf7Q==";

    String remark = "";
    int mMediaType = 0;

    private void initData() {
        String sipServer = (String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.SIP_SERVER, "");
        String token = (String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.TOKEN, "");
        String sdkId = (String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.SDK_ID, "");
        String remark = (String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.REMARK, "");
        String xToken = (String) SharePreferenceUtil.getInstance().getValue(AttrsConstant.X_TOKEN, "");
        int mediaType = (int) SharePreferenceUtil.getInstance().getValue(AttrsConstant.MEDIA_TYPE, 0);

        this.serverUrl = sipServer;
        this.SDK_TOKEN = token;
        this.sdkId = sdkId;
        this.remark = remark;
        this.X_TOKEN = xToken;
        this.mMediaType = mediaType;

        Log.e("fengzi", "initData: serverUrl" + this.serverUrl);
        Log.e("fengzi", "initData: SDK_TOKEN" + this.SDK_TOKEN);
        Log.e("fengzi", "initData: sdkId" + this.sdkId);
        Log.e("fengzi", "initData: remark" + this.remark);
        Log.e("fengzi", "initData: X_TOKEN" + this.X_TOKEN);
    }

    /**
     * 初始化Sip参数
     */
    private void initSipParam() {
        //"Ulaw;0", "Alaw;8", "ILbc;102", "Opus;120", "Agora;121",XYlink;122"
        int mDefaultCodec = 8;
        //"H264;127", "VP8;100", "VP9;101"
        int mDefaultVCodec = 127;
        boolean mSupportVideo = false;
        int mSipHeartBeatInterval = 8;
        //0: nolog 1:sipcore 2:sipstack 3:all
        int mTraceFlag = 3;
        //1:writelog 2:nologfile
        int mFileFlag = 1;

        //主叫号码设置
        mSipPhoneCtrl.SetNumber("1111");
        mSipPhoneCtrl.SetAuthName("1111");
        mSipPhoneCtrl.SetPassWord("00000000"); // 免登录模式 任意填但不要填空或者null
        mSipPhoneCtrl.SetDomain(serverUrl);
        mSipPhoneCtrl.SetServer(serverUrl);
        mSipPhoneCtrl.SetServerPort(5047);

        mSipPhoneCtrl.SetTraceFlag(mTraceFlag);
        mSipPhoneCtrl.SetFileFlag(mFileFlag);
        mSipPhoneCtrl.SetDefaultCodec(mDefaultCodec);
        mSipPhoneCtrl.SetDefaultVCodec(mDefaultVCodec);
        mSipPhoneCtrl.SetSurpportVedio(mSupportVideo);
        mSipPhoneCtrl.SetSipHeartBeatInterval(mSipHeartBeatInterval);
        //option方式发送心跳
        mSipPhoneCtrl.SetSipHeartBeatType(1);
        mSipPhoneCtrl.SetTimerType(SipCoreEvent.TimerType.TimerType_handle);
        mSipPhoneCtrl.SetAutoRegister(false);

        mSipPhoneCtrl.SetXPath("webcall");
        mSipPhoneCtrl.SetTransferMode(SipCoreEvent.TransferMode.TransferMode_Udp);
        WebSocketCtrl.setGmMode(false);

        mSipPhoneCtrl.SetMeidaType(mMediaType == 0 ? SipCoreEvent.MediaType.RTPVoice : SipCoreEvent.MediaType.WebrtcVoice);
        mSipPhoneCtrl.SetServiceKey("");
        mSipPhoneCtrl.SetLoadSingleMediaLib(true);
        mSipPhoneCtrl.SetCallStatics(true);
        mSipPhoneCtrl.SetMediaQualityDetect(true);
        //设置渲染模式
        mSipPhoneCtrl.SetVideoMode(SipCoreEvent.VideoMode.Webrtc_Fit);
        mSipPhoneCtrl.SetWebRtcCallMode(SipCoreEvent.WebrtcCallMode.WebrtcCall_Passive);
        mSipPhoneCtrl.SetSdkId(sdkId);//正式环境
        mSipPhoneCtrl.SetNetworkQualityDetect(true);
        mSipPhoneCtrl.SetRecordMediaStat(true);
        bindSipEvent();
    }


    /**
     * 绑定sip的通话事件
     */
    private void bindSipEvent() {
        mSipPhoneCtrl.RegisterEvent(new SipPhoneCtrl.IEvent() {

            @Override
            public void onCallStateChanged(SipCoreCall sipCoreCall, SipCoreEvent.CallState callState, String message) {
                Log.e("CallActivity", String.format("onCallStateChanged(%s,%s,%s)",
                        callState.toString(), sipCoreCall.mediaType.toString(), sipCoreCall.nCode));
                if (callState == CallState.OutgoingProgress) {
                    Log.e("CallActivity", String.format("外呼中:[%s]", sipCoreCall.sNum));
                    runOnUiThread(() -> textStatus.setText("外呼中"));
                } else if (callState == CallState.OutgoingRinging) {
                    Log.e("CallActivity", String.format("外呼对方振铃:[%s]", sipCoreCall.sNum));
                    runOnUiThread(() -> textStatus.setText("外呼对方振铃"));
                } else if (callState == CallState.Connected) {
                    Log.e("CallActivity", String.format("接通:[%s]", sipCoreCall.sNum));
                    runOnUiThread(() -> textStatus.setText("已接通"));
                    //默认免提
                    _mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSipPhoneCtrl.SetSpeakMode();
                        }
                    }, 500);
                } else if (callState == CallState.CallEnd || callState == CallState.CallReleased) {
                    finish();
                } else if (callState == CallState.Error) {
                    Log.e("CallActivity", String.format("error:[%d:%s]", sipCoreCall.nCode, sipCoreCall.sDescription));
                    finish();
                }
            }

            @Override
            public void onMediaConsultation(String key, String param) {

            }

            @Override
            public void onFacePositionChanged(int i, int i1, int faces) {
                //不加速通道的人脸识别回调
                Log.e("CallActivity", "非加速通道检测到人脸：" + faces + "时间戳：" + System.currentTimeMillis());
            }

            @Override
            public void onMessage(int i, String s) {
                //带内通信
            }

            @Override
            public void onInitialStatusChange(int i, String s) {
            }

            @Override
            public void onScreenRecord(String s) {
            }

            @Override
            public void onInfo(String s, String s1) {

            }

            @Override
            public void onDebugEvent(String s, String s1) {
            }

            @Override
            public void OnNetworkQuality(int qualityLevel, String qualityDesc) {
                super.OnNetworkQuality(qualityLevel, qualityDesc);
                Log.e("fengzi", "OnNetworkQuality: qualityLevel = " + qualityLevel + ",qualityDesc = " + qualityDesc);
            }

            @Override
            public void onMediaStatics(SipCoreEvent.VedioInfo vedioInfo) {
            }

            @Override
            public void onRegistrationStateChanged(SipCoreEvent.RegistrationState registrationState, String s) {
                //注册状态变化监听
            }
        });
    }


    /**
     * 相关按钮的事件
     *
     * @param v
     */
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_hand_off:
                mSipPhoneCtrl.Disconnect();
                break;
            case R.id.bt_mute:
                mMuted = !mMuted;
                int muteRes = mMuted ? R.drawable.icon_mute_active : R.drawable.icon_mute_inactive;
                btMute.setBackgroundResource(muteRes);
                mSipPhoneCtrl.Mute(mMuted);
                break;
            case R.id.bt_speaker:
                mSpeaker = !mSpeaker;
                int speakerRes = mSpeaker ? R.drawable.icon_speakerphone_active : R.drawable.icon_speakerphone_inactive;
                btSpeaker.setBackgroundResource(speakerRes);
                mSipPhoneCtrl.SetSpeakMode();
                break;
            default:
                break;
        }
    }

    /**
     * 初始化视图
     */
    private void initView() {
        textCallNo = findViewById(R.id.text_call_no);
        textStatus = findViewById(R.id.text_status);
        layoutInfo = findViewById(R.id.layout_info);
        remoteContainer = findViewById(R.id.remote_container);
        layoutTool = findViewById(R.id.layout_tool);
        btMute = findViewById(R.id.bt_mute);
        btAnswer = findViewById(R.id.bt_answer);
        btHandOff = findViewById(R.id.bt_hand_off);
        btSpeaker = findViewById(R.id.bt_speaker);

        Intent intent = getIntent();
        callNumber = intent.getStringExtra("callNumber");

        textCallNo.setText(callNumber);

        //设置点击事件
        btMute.setOnClickListener(this::onClick);
        btHandOff.setOnClickListener(this::onClick);
        btSpeaker.setOnClickListener(this::onClick);
    }


}